<template>
  <el-card>
    <template #header>账号列表</template>
    <div>
      <!-- 1.0 表格的数据渲染 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号" width="120">
        </el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column label="创建时间">
          <template v-slot="{ row }">
            {{ row.ctime | format }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 使用插槽显示按钮 -->
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="editUsers(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="delUser(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2.0 分页的处理 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 3.0 按钮的操作 -->
      <div style="margin-top: 20px">
        <el-button type="danger" size="mini" @click="delMore"
          >批量删除</el-button
        >
        <el-button type="primary" size="mini" @click="toggleSelection()"
          >取消选择</el-button
        >
      </div>
    </div>

    <!-- 编辑用户的提示框 -->
    <el-dialog title="账号编辑" :visible.sync="dialogVisible" width="40%">
      <!-- 弹窗的布局 -->
      <div>
        <el-form
          :model="editUser"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="60px"
          class="demo-ruleForm"
          size="mini"
        >
          <el-form-item label="账号" prop="account">
            <el-input
              type="text"
              v-model="editUser.account"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户组" prop="userGroup">
            <el-select v-model="editUser.userGroup" placeholder="请选择">
              <el-option label="超级管理员" value="超级管理员"> </el-option>
              <el-option label="普通管理员" value="普通管理员"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="submitEdit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import Aa from 'sortablejs'
import { accountList, delAccount, batchdel, editAccount } from '@/api/users.js'
import { validateAccount, validateGroup } from '@/utils/validate.js'

export default {
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      // 分页使用的数据
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      // 编辑用户的数据对象
      editUser: {
        account: '',
        userGroup: ''
      },
      // 编辑用户的规则对象
      rules: {
        account: [{ validator: validateAccount, trigger: 'blur' }],
        userGroup: [{ validator: validateGroup, trigger: 'change' }]
      }
    }
  },
  created() {
    this.getUsers()
  },
  mounted() {
    const el = document.querySelector('.el-table tbody')
    /* eslint-disable no-new */
    new Aa(el, {
      animation: 150
      // draggable: '.el-table__row'
    })
  },
  methods: {
    async getUsers() {
      const { data, total } = await accountList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      // console.log(data)
      this.tableData = data
      this.total = total
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUsers()
    },
    // 删除指定的用户
    delUser(id) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 删除成功的回调
          const { code } = await delAccount({ id })
          // console.log(data)
          if (code === 0) {
            this.getUsers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除
    delMore() {
      this.$confirm('此操作将永久删除这些账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 收集需要删除的数据id，然后发起请求
          const ids = this.multipleSelection.map(item => item.id)
          if (ids.length <= 0) return this.$message.error('选中内容为空')
          const { code } = await batchdel({
            ids: JSON.stringify(ids)
          })
          if (code === 0) {
            this.getUsers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑功能-回写数据
    editUsers(row) {
      // 使用对象拷贝的方式赋值
      this.editUser = { ...row }
      this.dialogVisible = true
    },
    // 提交修改
    async submitEdit() {
      const { code } = await editAccount(this.editUser)
      // console.log(data)
      if (code === 0) {
        this.getUsers()
        this.dialogVisible = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 178px;
}
</style>
